import json
import uuid

from django.views import View
from qiniu import Auth, put_data

from fiveapp import models
from .models import Famous_Teacher, College  # 导入模型
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .models import Student, Major, CarouselImage, Users, TemplateQuestionnaire
from rest_framework.views import APIView
from django.contrib.auth.hashers import make_password,check_password
from utils.jwttools import generate_jwt_token
from .serializers import TemplateQuestionnaireSerializer
from rest_framework.response import Response


def UpdateUserimg(request):
    # 接受前端传来的图片
    file = request.FILES.get('file')
    if not file:
        return JsonResponse({'error': '未上传文件'}, status=400)

        # 2. 验证文件类型
    if file.content_type not in ['image/jpeg', 'image/png']:
        return JsonResponse({'error': '仅支持JPEG/PNG格式'}, status=400)

    # 上传到七牛云
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'dKq7dAAEFBO7q_DPQHkagG69zsv9pkhHq26DCtUD'
    secret_key = 'zrZL2XO-Sqkg7UKdzawBvZK0t0WUIrStPmgbvJKt'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'liuchong-project-demo'
    # 上传后保存的文件名
    key = file.name
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    ret, info = put_data(token, key, file.read())
    print(ret, info)
    print(ret['hash'])
    if info.status_code == 200:
        # 上传成功，返回图片的外链url

        return JsonResponse({'url': 'http://sxlakuwuo.hd-bkt.clouddn.com/' + key}, status=200)
    else:
        return JsonResponse({'error': '上传失败'}, status=500)
# 讲师类函数（张默涵——增删改查）
class FamousTeacherView(View):
    http_method_names = ['get', 'post']

    def get(self, request):
        blogs = Famous_Teacher.objects.select_related('college_name').all()
        data = []
        for blog in blogs:
            data.append({
                'id': blog.id,
                'name': blog.teacher_name,
                'position': blog.teacher_position,
                'introduce': blog.teacher_introduce,
                'image': blog.teacher_image,
                'skill': blog.teacher_skill,
                'college': {
                    'college': blog.college_name.college_name,
                }
            })
        return JsonResponse({'data': data, 'msg': '获取教师信息成功'}, safe=False, status=200)

    def post(self, request):
        try:
            data = json.loads(request.body)

            teacher_name = data.get('teacher_name')
            teacher_position = data.get('teacher_position')
            teacher_introduce = data.get('teacher_introduce')
            teacher_skill = data.get('teacher_skill')
            college_name = data.get('college_name')
            teacher_image = data.get('teacher_image')

            required_fields = [
                teacher_name,
                teacher_position,
                teacher_introduce,
                college_name,
                teacher_skill,
                teacher_image
            ]
            if not all(required_fields):
                return JsonResponse(
                    {'message': '姓名、职位、简介、学院名称、技能、图片地址 不能为空'},
                    status=400
                )

            college, created = College.objects.get_or_create(
                college_name=college_name
            )

            famous_teacher = Famous_Teacher.objects.create(
                teacher_name=teacher_name,
                teacher_position=teacher_position,
                teacher_introduce=teacher_introduce,
                teacher_skill=teacher_skill,
                teacher_image=teacher_image,
                college_name=college
            )

            return JsonResponse(
                {'message': '添加成功', 'data': {
                    'id': famous_teacher.id,
                    'teacher_name': famous_teacher.teacher_name
                }},
                status=201
            )

        except json.JSONDecodeError:
            return JsonResponse(
                {'message': '无效的 JSON 格式，请检查请求体'},
                status=400
            )
        except Exception as e:
            return JsonResponse(
                {'message': f'添加失败：{str(e)}'},
                status=500
            )

class TeacherDetailView(View):
    http_method_names = ['delete', 'put']

    def delete(self, request, teacher_id):
        try:
            teacher = Famous_Teacher.objects.get(id=teacher_id)
        except Famous_Teacher.DoesNotExist:
            return JsonResponse(
                {'message': f'教师ID {teacher_id} 不存在'},
                status=404
            )

        teacher.delete()

        return JsonResponse(
            {'message': f'教师ID {teacher_id} 删除成功'},
            status=200
        )

    def put(self, request, teacher_id):
        try:
            teacher = Famous_Teacher.objects.get(id=teacher_id)

            data = json.loads(request.body)
            teacher_name = data.get('teacher_name')
            teacher_position = data.get('teacher_position')
            teacher_introduce = data.get('teacher_introduce')
            teacher_skill = data.get('teacher_skill')
            college_name = data.get('college_name')
            teacher_image = data.get('teacher_image')

            required_fields = [
                teacher_name,
                teacher_position,
                teacher_introduce,
                college_name,
                teacher_skill,
                teacher_image
            ]
            if not all(required_fields):
                return JsonResponse(
                    {'message': '姓名、职位、简介、学院名称、技能、图片地址 不能为空'},
                    status=400
                )

            college, created = College.objects.get_or_create(
                college_name=college_name
            )
            teacher.teacher_name = teacher_name
            teacher.teacher_position = teacher_position
            teacher.teacher_introduce = teacher_introduce
            teacher.teacher_skill = teacher_skill
            teacher.teacher_image = teacher_image
            teacher.college_name = college
            teacher.save()

            return JsonResponse(
                {'message': '编辑成功', 'data': {
                    'id': teacher.id,
                    'teacher_name': teacher.teacher_name
                }},
                status=200
            )

        except json.JSONDecodeError:
            return JsonResponse(
                {'message': '无效的 JSON 格式，请检查请求体'},
                status=400
            )
        except Famous_Teacher.DoesNotExist:
            return JsonResponse(
                {'message': f'教师ID {teacher_id} 不存在'},
                status=404
            )
        except Exception as e:
            return JsonResponse(
                {'message': f'编辑失败：{str(e)}'},
                status=500
            )


class ProfessionOper(View):
    def get(self, request):
        college = request.GET.get('college')

        try:
            if college:
                # 查询指定学院的信息
                college_obj = models.College.objects.get(college_name=college)
                teachers = list(models.Famous_Teacher.objects.filter(
                    college_name_id=college_obj.id
                ).values())

                professions = list(models.Profession.objects.filter(
                    profession_Forkey_id=college_obj.id
                ).values())

                return JsonResponse({
                    'teachers': teachers,
                    'professions_info': professions
                }, status=200)

            else:
                # 返回所有数据
                professions = list(models.Profession.objects.all().values())
                imgs = list(models.Profession_img.objects.all().values())

                return JsonResponse({
                    'profession_info': professions,
                    'profession_img': imgs
                }, status=200)

        except models.College.DoesNotExist:
            return JsonResponse({'error': 'College not found'}, status=404)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    def post(self, request):
        try:
            data = json.loads(request.body)

            # 创建学院
            college = models.College.objects.create(
                college_name=data['name']
            )

            # 创建专业（关联学院ID）
            profession = models.Profession.objects.create(
                profession_Forkey_id=college.id,
                name=data.get('name'),
                profession_location=data.get('profession_location'),
                profession_profile=data.get('profession_profile'),
                profession_course=data.get('profession_course'),
                profession_image=data.get('profession_image'),
                profession_image_text=data.get('profession_image_text')
            )

            return JsonResponse({
                'success': True,
                'college_id': college.id,
                'profession_id': profession.id
            }, status=201)

        except KeyError as e:
            return JsonResponse({'error': f'Missing field: {str(e)}'}, status=400)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    def put(self, request):
        try:
            data = json.loads(request.body)
            profession_id = data.get('id')

            if not profession_id:
                return JsonResponse({'error': 'ID is required'}, status=400)

            profession = models.Profession.objects.get(id=profession_id)

            # 更新字段
            for field in ['name', 'profession_location', 'profession_profile',
                          'profession_course', 'profession_image', 'profession_image_text']:
                if field in data:
                    setattr(profession, field, data[field])

            profession.save()
            return JsonResponse({'status': 'success'})

        except models.Profession.DoesNotExist:
            return JsonResponse({'error': 'Profession not found'}, status=404)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    def delete(self, request):
        try:
            data = json.loads(request.body)
            id = data['id']

            # 级联删除（先删专业，再删学院）
            profession = models.Profession.objects.get(profession_Forkey_id=id)
            profession.delete()

            college = models.College.objects.get(id=id)
            college.delete()

            return JsonResponse({
                'success': True,
                'message': 'Deleted successfully'
            }, status=200)

        except (models.Profession.DoesNotExist, models.College.DoesNotExist):
            return JsonResponse({'error': 'Data not found'}, status=404)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
def get_students(request):
    # 获取所有学生数据
    students = Student.objects.all().values(
        'id',
        'name',
        'salary',
        'photo',
        'company',
        'major__name'  # 获取关联专业名称
    )

    print(students,"ceshi><><>")
    # 打印到控制台
    print("===== 学生数据 =====")
    for student in students:
        print(json.dumps(student, indent=2, ensure_ascii=False))

    return JsonResponse(list(students), safe=False)


class AddStudentView(View):
    def post(self, request):
        try:
            # 解析请求数据
            data = json.loads(request.body.decode('utf-8'))
            print("前端传过来的 major 数据:", data['major'])
            # 验证必要字段
            required_fields = ['name', 'salary', 'photo', 'company', 'major']
            for field in required_fields:
                if field not in data:
                    return JsonResponse({'error': f'缺少必要字段: {field}'}, status=400)

            # 获取专业对象（动态从请求中获取）
            try:
                major = Major.objects.get(name=data['major'])
            except Major.DoesNotExist:
                return JsonResponse({'error': f'专业 "{data["major"]}" 不存在'}, status=400)

            # 创建学生对象
            student = Student(
                name=data['name'],
                salary=data['salary'],
                photo=data['photo'],  # 注意：如果是文件上传，需要不同的处理方式
                company=data['company'],
                major=major
            )
            print("34567890-098654334567890-09876543456789", major)
            student.save()

            # 返回成功响应
            return JsonResponse({'msg': '添加成功', 'id': student.id}, status=201)

        except Exception as e:
            # 通用错误处理（生产环境可以记录日志）
            return JsonResponse({'error': f'服务器错误: {str(e)}'}, status=500)


class EditStudentView(View):
    def post(self, request):
        try:
            # 解析请求数据
            data = json.loads(request.body.decode('utf-8'))

            # 验证必要字段
            required_fields = ['id', 'name', 'salary', 'photo', 'company', 'major']
            for field in required_fields:
                if field not in data:
                    return JsonResponse({'error': f'缺少必要字段: {field}'}, status=400)

            # 获取要编辑的学生
            try:
                student = Student.objects.get(id=data['id'])
            except Student.DoesNotExist:
                return JsonResponse({'error': f'学生 ID {data["id"]} 不存在'}, status=404)

            # 获取专业对象（动态从请求中获取）
            try:
                major = Major.objects.get(name=data['major'])
            except Major.DoesNotExist:
                return JsonResponse({'error': f'专业 "{data["major"]}" 不存在'}, status=400)

            # 更新学生信息
            student.name = data['name']
            student.salary = data['salary']
            student.photo = data['photo']  # 注意：如果是文件上传，需要不同的处理方式
            student.company = data['company']
            student.major = major
            student.save()

            # 返回成功响应
            return JsonResponse({'msg': '更新成功'}, status=200)

        except json.JSONDecodeError:
            return JsonResponse({'error': '无效的JSON数据'}, status=400)
        except Exception as e:
            # 通用错误处理
            return JsonResponse({'error': f'服务器错误: {str(e)}'}, status=500)


def get_majors(request):
    # 获取所有专业数据
    majors = Major.objects.all().values('id', 'name')

    # 打印到控制台
    print("===== 专业数据 =====")
    for major in majors:
        print(json.dumps(major, indent=2, ensure_ascii=False))

    return JsonResponse(list(majors), safe=False)


def get_carousel(request):
    # 从数据库获取轮播图数据
    carousels = CarouselImage.objects.all().values('id', 'photo')

    # 打印数据（可选）
    for carousel in carousels:
        print(json.dumps(carousel, indent=2, ensure_ascii=False))

    # 返回所有轮播图数据
    return JsonResponse(list(carousels), safe=False)


# 登录注册函数
class RegisterView(View):
    def post(self,request):
        # 接受用户的账号和密码
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')
        phone = data.get('username')
        user_type = data.get('user_type')
        print("><<><>",user_type)
        # 判断账号是否存在
        if Users.objects.filter(username=username).exists():
            return JsonResponse({'code': 1, 'msg': '账号已存在'},safe=False)
        # 保存账号和密码
        # 密码加密
        hash_password = make_password(password)
        Users.objects.create(username=username,password=hash_password,phone=phone,user_type=user_type)
        return JsonResponse({'code': 0, 'msg': '注册成功'},safe=False)

class LoginView(View):
    def post(self,request):
        # 接受用户的账号和密码
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')
        # 判断账号是否存在
        if not Users.objects.filter(username=username).exists():
            return JsonResponse({'code': 400, 'msg': '账号不存在'},safe=False)
        # 判断密码是否正确
        user = Users.objects.get(username=username)
        print("登录手机号：：》》》",user.username)
        if not check_password(password,user.password):
            return JsonResponse({'code': 400, 'msg': '密码错误'},safe=False)
        # 生成token
        payload = {'username': username}
        # token = generate_jwt_token(payload)        # 在前端存储用户名
        response = JsonResponse({'code': 0, 'msg': '登录成功',"token":"Bear "},safe=False)
        response.set_cookie('username', username)  # 可以使用cookie存储
        return response

class UserInfoView(View):
    def get(self,request):
        return JsonResponse({'code': 0, 'msg': '获取用户信息成功'},safe=False)


class TemplateListView(APIView):
    def get(self, request):
        templates = TemplateQuestionnaire.objects.all()
        serializer = TemplateQuestionnaireSerializer(templates, many=True)
        return Response(serializer.data)


class UserPhoneInfoView(View):
    def get(self, request):
        # 获取请求中的用户名
        # print("get>>",request.GET.get('phone'))
        username = request.GET.get('phone')
        print(">>+<<",username)
        try:
            # 根据用户名查找用户
            user = Users.objects.get(username=username)
            print(">>>",user)
            # 获取用户的手机号
            phone = user.phone
            if phone:
                return JsonResponse({'code': 0, 'msg': '获取用户手机号成功', 'phone': phone}, safe=False)
            else:
                return JsonResponse({'code': 404, 'msg': '用户手机号未设置'}, safe=False)
        except Users.DoesNotExist:
            return JsonResponse({'code': 404, 'msg': '用户不存在'}, safe=False)


# 用户管理（王世博——用户管理的增删改查）
class UserView(View):
    http_method_names = ['get', 'post']

    def get(self, request):
        """获取用户列表"""
        users = Users.objects.all()
        data = []
        for user in users:
            data.append({
                'id': user.id,
                'username': user.username,
                'phone': user.phone,
                'user_type': user.user_type,
            })
        return JsonResponse({'data': data, 'msg': '获取用户信息成功'}, safe=False, status=200)

    def post(self, request):
        """添加用户的那个逻辑处理"""
        try:
            data = json.loads(request.body)

            username = data.get('username')
            password = data.get('password')
            user_type = data.get('user_type')

            required_fields = [username, password, user_type]
            if not all(required_fields):
                return JsonResponse(
                    {'message': '用户名、密码和用户类型不能为空'},
                    status=400
                )

            # i看这个用户名是否已存在
            if Users.objects.filter(username=username).exists():
                return JsonResponse(
                    {'message': f'用户名 {username} 已存在'},
                    status=400
                )

            # 创建用户，phone 自动设置为 username
            user = Users.objects.create(
                username=username,
                password=make_password(password),  # 加密存储密码
                phone=username,  # phone 字段自动设置为与 username 相同
                user_type=user_type
            )

            return JsonResponse(
                {'message': '添加成功', 'data': {
                    'id': user.id,
                    'username': user.username,
                    'phone': user.phone,
                    'user_type': user.user_type
                }},
                status=201
            )

        except json.JSONDecodeError:
            return JsonResponse(
                {'message': '无效的 JSON 格式，请检查请求体'},
                status=400
            )
        except Exception as e:
            return JsonResponse(
                {'message': f'添加失败：{str(e)}'},
                status=500
            )



class UserDetailView(View):
    http_method_names = ['delete', 'put']

    def delete(self, request, user_id):
        """删除用户"""
        try:
            user = Users.objects.get(id=user_id)
        except Users.DoesNotExist:
            return JsonResponse(
                {'message': f'用户ID {user_id} 不存在'},
                status=404
            )

        user.delete()

        return JsonResponse(
            {'message': f'用户ID {user_id} 删除成功'},
            status=200
        )

    def put(self, request, user_id):
        """更新用户信息"""
        try:
            user = Users.objects.get(id=user_id)

            data = json.loads(request.body)
            username = data.get('username', user.username)
            password = data.get('password')
            user_type = data.get('user_type', user.user_type)

            # 验证必填字段
            if not username or not user_type:
                return JsonResponse(
                    {'message': '用户名和用户类型不能为空'},
                    status=400
                )

            # 检查新用户名是否已存在（排除当前用户）
            if username != user.username and Users.objects.filter(username=username).exists():
                return JsonResponse(
                    {'message': f'用户名 {username} 已存在'},
                    status=400
                )

            # 更新用户信息
            user.username = username
            user.phone = username  # 确保 phone 与 username 一致
            user.user_type = user_type

            # 如果提供了新密码，则更新密码
            if password:
                user.password = make_password(password)

            user.save()

            return JsonResponse(
                {'message': '编辑成功', 'data': {
                    'id': user.id,
                    'username': user.username,
                    'phone': user.phone,
                    'user_type': user.user_type
                }},
                status=200
            )

        except json.JSONDecodeError:
            return JsonResponse(
                {'message': '无效的 JSON 格式，请检查请求体'},
                status=400
            )
        except Users.DoesNotExist:
            return JsonResponse(
                {'message': f'用户ID {user_id} 不存在'},
                status=404
            )
        except Exception as e:
            return JsonResponse(
                {'message': f'编辑失败：{str(e)}'},
                status=500
            )